import os
import json
from flask import Flask, request, render_template_string, jsonify

from basic.config import GlobalInfo, GlobalCfg
from modules.module import WebsiteModule  # 假设这是 WebsiteModule 的路径

class GiteeID(WebsiteModule):
    def __init__(self, parent):
        super().__init__(parent, 'GiteeID', 'giteeid与工号的映射程序')
        self.json_file_path = GlobalCfg.giteeid_cfg
        
        # 添加用于显示页面的 GET 路由
        self.add_routes('GiteeIDlist', '/GiteeIDlist', self.homepage, methods=['GET'])
        # 添加用于处理表单提交的 POST 路由
        self.add_routes('GiteeIDupdate', '/GiteeIDupdate', self.update_json, methods=['POST'])

    def homepage(self):
        # 检查 JSON 文件是否存在
        if not os.path.exists(self.json_file_path):
            return jsonify({"error": "JSON 文件不存在"}), 404

        with open(self.json_file_path, 'r', encoding='utf-8') as json_file:
            json_data = json.load(json_file)
            sorted_json_data = {k: json_data[k] for k in sorted(json_data)}

        return render_template_string(self.html_template, json_data=sorted_json_data)
    
    def update_json(self):
        gitee_id = request.form['gitee_id']
        work_id = request.form['work_id']

        if not gitee_id or not work_id:
            return "GITEE ID 和工号不能为空！", 400

        # 读取现有的 JSON 数据
        if not os.path.exists(self.json_file_path):
            json_data = {}
        else:
            with open(self.json_file_path, 'r', encoding='utf-8') as json_file:
                json_data = json.load(json_file)

        # 更新 JSON 数据
        json_data[gitee_id] = work_id

        # 将更新后的 JSON 数据写回文件
        with open(self.json_file_path, 'w', encoding='utf-8') as f:
            json.dump(json_data, f, indent=4, ensure_ascii=False)

        return render_template_string(self.html_template, json_data=json_data)

    @property
    def html_template(self):
        # HTML 模板
        return """
        <!DOCTYPE html>
        <html>
        <head>
            <title>GITEE ID&工号(for小鲁班推送门禁结果)</title>
        </head>
        <body>
            <div class="container">
                <a href='/'>返回首页</a><br>
                <h1>GITEE ID&工号(for小鲁班推送门禁结果)</h1>
                <table>
                    <tr>
                        <th>GITEE ID</th>
                        <th>工号</th>
                    </tr>
                    {% for gitee_id, work_id in json_data.items() %}
                    <tr>
                        <td>{{ gitee_id }}</td>
                        <td>{{ work_id }}</td>
                    </tr>
                    {% endfor %}
                </table>
                <h2>添加/更新</h2>
                <form method="post" action="/GiteeIDupdate">
                    GITEE ID: <input type="text" name="gitee_id"><br>
                    工号: <input type="text" name="work_id"><br>
                    <input type="submit" value="提交">
                </form>
            </div>
        </body>
        </html>
        """


if __name__ == '__main__':
    giteeID_module = GiteeID()
    giteeID_module.run()